package com.tools;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;

import java.io.FileInputStream;
import java.util.Scanner;

public class SaveData {
    JedisPool jedisPool = new JedisPool("localhost", 6379);

    public void saveRat() {
        String path = "/home/mingyi/桌面/bjtu/ml-25m/data/rat80.csv";
        try (FileInputStream inputStream = new FileInputStream(path);
             Scanner sc = new Scanner(inputStream); Jedis jedis = jedisPool.getResource()) {
            Pipeline p = jedis.pipelined();
            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                String[] strArray = line.split(",");
                String key = "fr:uid:" + strArray[0]; // fr是film recommendation 的简写
                String field = strArray[2];
                Response<String> value = p.hget(key, field);
                if (value == null) {
                    p.hset(key, field, strArray[1]);
                } else {
                    p.hset(key, field, value + "," + strArray[1]);
                }
            }
            p.sync();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void saveMovie() {
        String path = "/home/mingyi/桌面/bjtu/ml-25m/genome-scores.csv";
        try (FileInputStream inputStream = new FileInputStream(path);
             Scanner sc = new Scanner(inputStream); Jedis jedis = jedisPool.getResource()) {
            Pipeline p = jedis.pipelined();
            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                String[] strArray = line.split(",");
                String key = "fr:mid:" + strArray[0]; // fr是film recommendation 的简写
                String field = strArray[1];
                Response<String> value = p.hget(key, field);
                if (value == null) {
                    p.hset(key, field, strArray[2]);
                } else {
                    p.hset(key, field, value + "," + strArray[2]);
                }
            }
            p.sync();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void saveMovieTag() {
        String path = "/home/mingyi/桌面/bjtu/ml-25m/genome-tags.csv";
        try (FileInputStream inputStream = new FileInputStream(path);
             Scanner sc = new Scanner(inputStream); Jedis jedis = jedisPool.getResource()) {
            Pipeline p = jedis.pipelined();
            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                String[] strArray = line.split(",");
                String key = "fr:tag:" + strArray[0]; // fr是film recommendation 的简写
                String value = strArray[1];
                p.set(key, value);
            }
            p.sync();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
